package com.co;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

/**
 * @author 董老师
 * @date 2021/4/17
 */
public class SearchExpressNoDemo2 {
    
    @Test
    public void expressTest() throws IOException {
        StringBuilder url = new StringBuilder("https://jisuexpress.api.bdymkt.com/express/query")
                .append("?").append("type=").append("auto")
                .append("&").append("number=").append("75454479418202")
                .append("&").append("mobile=").append("15129210947");
        
        OkHttpClient okhttpclient = new OkHttpClient.Builder().build();
        
        RequestBody requestbody = RequestBody.create("", MediaType.parse("text/html"));
        Request request = new Request.Builder()
                .url(url.toString())
                .method("POST", requestbody)
                .addHeader("X-Bce-Signature", "AppCode/053e1d7b056545bca03483b7e0b21ed0")
                .build();
        Response response = okhttpclient.newCall(request).execute();
        
        Assert.assertEquals(200, response.code());
        
        ResponseBody body = response.body();
        Assert.assertNotNull("response body is null", body);
        
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(body.string(), JsonObject.class);
        
        //断言
        int status = jsonObject.get("status").getAsInt();
        Assert.assertEquals("response body $.status expected 0", 0, status);
        
        String msg = jsonObject.get("msg").getAsString();
        Assert.assertEquals("response body $.msg expected ok", "ok", msg);
        
        JsonObject result = jsonObject.get("result").getAsJsonObject();
        Assert.assertNotNull("response body  $.result expected not null", result);
        
        Assert.assertTrue("response body $.result.logo expected exists", result.has("logo"));
        
        /*
             list key不存在，返回null
             list key存在的，值null， 返回Json null
         */
        if (!result.has("list")) {
            Assert.fail("response body $.result.list not exists");
        }
        JsonElement listElement = result.get("list");
        if (listElement.isJsonNull()) {
            Assert.fail("response body $.result.list value is null");
        }
        JsonArray expressLines = listElement.getAsJsonArray();
        if (expressLines.size() > 0) {
            Assert.assertEquals("2021-04-12 19:31:26", expressLines.get(0).getAsJsonObject().get("time").getAsString());
        } else {
            Assert.fail("response body $.result.list length is zero");
        }
    }
}
